<template>
  <div class="permission-list-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
      <div class="header-title">
            <el-icon><Key /></el-icon>
            <span>权限管理</span>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd" plain>
              <el-icon><Plus /></el-icon>添加权限
            </el-button>
            <el-button @click="fetchData" plain>
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="illustration-container">
        <img src="https://img.icons8.com/color/96/000000/key-security.png" alt="Permission Management Illustration" class="illustration-image">
        <div class="illustration-text">
          <h3>系统权限管理</h3>
          <p>管理系统功能权限点，控制用户访问权限</p>
      </div>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>权限列表</span>
          <el-tag type="info">共 {{ getPermissionCount(tableData) }} 条记录</el-tag>
    </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        stripe
        highlight-current-row
        :header-cell-style="{background:'#f5f7fa', color:'#606266'}"
        :empty-text="'暂无权限数据'"
      >
        
        <el-table-column prop="name" label="权限名称" width="200">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon v-if="scope.row.type === 'menu'"><Menu /></el-icon>
              <el-icon v-else-if="scope.row.type === 'button'"><Mouse /></el-icon>
              <el-icon v-else-if="scope.row.type === 'api'"><Connection /></el-icon>
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="权限编码" width="200">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Document /></el-icon>
              <span>{{ scope.row.code }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 'menu'" type="success">菜单</el-tag>
            <el-tag v-else-if="scope.row.type === 'button'" type="info">按钮</el-tag>
            <el-tag v-else-if="scope.row.type === 'api'" type="warning">接口</el-tag>
            <el-tag v-else>{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
       
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <div class="operation-buttons">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(scope.row)"
                text
              >
                <el-icon><Edit /></el-icon>编辑
              </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="hasChildren(scope.row)"
                text
              >
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑权限对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加权限' : '编辑权限'" width="600px">
      <el-form
        :model="permissionForm"
        :rules="permissionRules"
        ref="permissionFormRef"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="permissionForm.code" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型">
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
            <el-option label="接口" value="api" />
          </el-select>
        </el-form-item>
      
        <el-form-item label="上级权限" prop="parentId">
          <el-tree-select
            v-model="permissionForm.parentId"
            :data="permissionTree"
            check-strictly
            node-key="id"
            :render-after-expand="false"
            :props="{
              label: 'name',
              children: 'children'
            }"
            placeholder="请选择上级权限"
            clearable
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="permissionForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="permissionForm.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Plus, 
  Refresh, 
  Key, 
  Edit, 
  Delete, 
  Document, 
  Menu,
  Mouse,
  Connection
} from '@element-plus/icons-vue';
import axios from 'axios';

// 数据加载状态
const loading = ref(false);
const submitLoading = ref(false);

// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '小区管理',
    code: 'community:view',
    type: 'menu',
    path: 'property/community',
    description: '小区基本信息管理',
    children: [
      { id: 101, name: '查看小区列表', code: 'community:list', type: 'button', path: '', description: '查看小区列表' },
      { id: 102, name: '添加小区', code: 'community:add', type: 'button', path: '', description: '添加小区信息' },
      { id: 103, name: '编辑小区', code: 'community:edit', type: 'button', path: '', description: '编辑小区信息' },
      { id: 104, name: '删除小区', code: 'community:delete', type: 'button', path: '', description: '删除小区信息' }
    ]
  },
  {
    id: 2,
    name: '房产管理',
    code: 'building:view',
    type: 'menu',
    path: 'property/building',
    description: '楼宇和房产信息管理',
    children: [
      { id: 201, name: '查看栋数列表', code: 'building:list', type: 'button', path: '', description: '查看栋数列表' },
      { id: 202, name: '添加栋数', code: 'building:add', type: 'button', path: '', description: '添加栋数信息' },
      { id: 203, name: '编辑栋数', code: 'building:edit', type: 'button', path: '', description: '编辑栋数信息' },
      { id: 204, name: '删除栋数', code: 'building:delete', type: 'button', path: '', description: '删除栋数信息' },
      { id: 205, name: '查看房产列表', code: 'home:list', type: 'button', path: '', description: '查看房产列表' },
      { id: 206, name: '添加房产', code: 'home:add', type: 'button', path: '', description: '添加房产信息' },
      { id: 207, name: '编辑房产', code: 'home:edit', type: 'button', path: '', description: '编辑房产信息' },
      { id: 208, name: '删除房产', code: 'home:delete', type: 'button', path: '', description: '删除房产信息' }
    ]
  },
  {
    id: 3,
    name: '人员管理',
    code: 'personnel:view',
    type: 'menu',
    path: 'property/personnel',
    description: '业主和车辆信息管理',
    children: [
      { id: 301, name: '查看业主列表', code: 'owner:list', type: 'button', path: '', description: '查看业主列表' },
      { id: 302, name: '添加业主', code: 'owner:add', type: 'button', path: '', description: '添加业主信息' },
      { id: 303, name: '编辑业主', code: 'owner:edit', type: 'button', path: '', description: '编辑业主信息' },
      { id: 304, name: '删除业主', code: 'owner:delete', type: 'button', path: '', description: '删除业主信息' },
      { id: 305, name: '查看车辆列表', code: 'vehicle:list', type: 'button', path: '', description: '查看车辆列表' },
      { id: 306, name: '添加车辆', code: 'vehicle:add', type: 'button', path: '', description: '添加车辆信息' },
      { id: 307, name: '编辑车辆', code: 'vehicle:edit', type: 'button', path: '', description: '编辑车辆信息' },
      { id: 308, name: '删除车辆', code: 'vehicle:delete', type: 'button', path: '', description: '删除车辆信息' }
    ]
  },
  {
    id: 4,
    name: '车位管理',
    code: 'parking:view',
    type: 'menu',
    path: 'property/parking',
    description: '车位和使用记录管理',
    children: [
      { id: 401, name: '查看车位列表', code: 'parking:list', type: 'button', path: '', description: '查看车位列表' },
      { id: 402, name: '添加车位', code: 'parking:add', type: 'button', path: '', description: '添加车位信息' },
      { id: 403, name: '编辑车位', code: 'parking:edit', type: 'button', path: '', description: '编辑车位信息' },
      { id: 404, name: '删除车位', code: 'parking:delete', type: 'button', path: '', description: '删除车位信息' },
      { id: 405, name: '查看使用记录', code: 'parking:usage:list', type: 'button', path: '', description: '查看车位使用记录' },
      { id: 406, name: '添加使用记录', code: 'parking:usage:add', type: 'button', path: '', description: '添加车位使用记录' },
      { id: 407, name: '编辑使用记录', code: 'parking:usage:edit', type: 'button', path: '', description: '编辑车位使用记录' },
      { id: 408, name: '删除使用记录', code: 'parking:usage:delete', type: 'button', path: '', description: '删除车位使用记录' }
    ]
  },
  {
    id: 5,
    name: '服务管理',
    code: 'service:view',
    type: 'menu',
    path: 'property/service',
    description: '活动、报修、投诉和信箱管理',
    children: [
      { id: 501, name: '查看活动列表', code: 'activity:list', type: 'button', path: '', description: '查看活动列表' },
      { id: 502, name: '添加活动', code: 'activity:add', type: 'button', path: '', description: '添加活动信息' },
      { id: 503, name: '编辑活动', code: 'activity:edit', type: 'button', path: '', description: '编辑活动信息' },
      { id: 504, name: '删除活动', code: 'activity:delete', type: 'button', path: '', description: '删除活动信息' },
      { id: 505, name: '查看报修列表', code: 'repair:list', type: 'button', path: '', description: '查看报修列表' },
      { id: 506, name: '处理报修', code: 'repair:process', type: 'button', path: '', description: '处理报修请求' },
      { id: 507, name: '查看投诉列表', code: 'complaint:list', type: 'button', path: '', description: '查看投诉列表' },
      { id: 508, name: '处理投诉', code: 'complaint:process', type: 'button', path: '', description: '处理投诉请求' },
      { id: 509, name: '查看信箱列表', code: 'mailbox:list', type: 'button', path: '', description: '查看信箱列表' },
      { id: 510, name: '回复信箱', code: 'mailbox:reply', type: 'button', path: '', description: '回复信箱消息' }
    ]
  },
  {
    id: 6,
    name: '系统管理',
    code: 'system:view',
    type: 'menu',
    path: 'system',
    description: '用户、角色和权限管理',
    children: [
      { id: 601, name: '查看用户列表', code: 'user:list', type: 'button', path: '', description: '查看用户列表' },
      { id: 602, name: '添加用户', code: 'user:add', type: 'button', path: '', description: '添加用户信息' },
      { id: 603, name: '编辑用户', code: 'user:edit', type: 'button', path: '', description: '编辑用户信息' },
      { id: 604, name: '删除用户', code: 'user:delete', type: 'button', path: '', description: '删除用户信息' },
      { id: 605, name: '查看角色列表', code: 'role:list', type: 'button', path: '', description: '查看角色列表' },
      { id: 606, name: '添加角色', code: 'role:add', type: 'button', path: '', description: '添加角色信息' },
      { id: 607, name: '编辑角色', code: 'role:edit', type: 'button', path: '', description: '编辑角色信息' },
      { id: 608, name: '删除角色', code: 'role:delete', type: 'button', path: '', description: '删除角色信息' },
      { id: 609, name: '查看权限列表', code: 'permission:list', type: 'button', path: '', description: '查看权限列表' },
      { id: 610, name: '权限配置', code: 'permission:config', type: 'button', path: '', description: '配置权限信息' }
    ]
  }
]);

// 计算属性：权限树形结构（用于选择上级权限）
const permissionTree = computed(() => {
  // 添加一个根节点选项
  return [
    { id: 0, name: '根权限', children: tableData.value }
  ];
});

// 权限表单
const permissionForm = reactive({
  id: null,
  name: '',
  code: '',
  type: 'menu',
  path: '',
  parentId: null,
  sort: 0,
  description: ''
});

// 表单验证规则
const permissionRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { pattern: /^[a-z]+:[a-z]+(:?[a-z]+)?$/, message: '权限编码格式应为module:action', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
};

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const permissionFormRef = ref(null);

// 初始化
onMounted(() => {
  fetchData();
});

// 获取权限列表数据
const fetchData = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    const response = await axios.get('/api/permissions', {
      headers: { Authorization: `Bearer ${token}` }
    });
    
    // 处理后端返回的数据
    if (response.data) {
      tableData.value = response.data;
    } else {
      // 如果后端API未实现，使用模拟数据
      tableData.value = [
        {
          id: 1,
          name: '小区管理',
          code: 'community:view',
          type: 'menu',
          path: 'property/community',
          description: '小区基本信息管理',
          children: [
            { id: 101, name: '查看小区列表', code: 'community:list', type: 'button', path: '', description: '查看小区列表' },
            { id: 102, name: '添加小区', code: 'community:add', type: 'button', path: '', description: '添加小区信息' },
            { id: 103, name: '编辑小区', code: 'community:edit', type: 'button', path: '', description: '编辑小区信息' },
            { id: 104, name: '删除小区', code: 'community:delete', type: 'button', path: '', description: '删除小区信息' }
          ]
        },
        // 其他权限数据保持不变...
      ];
    }
  } catch (error) {
    console.error('获取权限列表失败:', error);
    ElMessage.error('获取权限列表失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    
    // 使用模拟数据作为备选
    tableData.value = [
      {
        id: 1,
        name: '小区管理',
        code: 'community:view',
        type: 'menu',
        path: 'property/community',
        description: '小区基本信息管理',
        children: [
          { id: 101, name: '查看小区列表', code: 'community:list', type: 'button', path: '', description: '查看小区列表' },
          { id: 102, name: '添加小区', code: 'community:add', type: 'button', path: '', description: '添加小区信息' },
          { id: 103, name: '编辑小区', code: 'community:edit', type: 'button', path: '', description: '编辑小区信息' },
          { id: 104, name: '删除小区', code: 'community:delete', type: 'button', path: '', description: '删除小区信息' }
        ]
      },
      // 保留现有的模拟数据...
    ];
  } finally {
    loading.value = false;
  }
};

// 添加权限
const handleAdd = () => {
  dialogType.value = 'add';
  resetPermissionForm();
  dialogVisible.value = true;
};

// 编辑权限
const handleEdit = (row) => {
  dialogType.value = 'edit';
  resetPermissionForm();
  
  // 填充表单
  Object.keys(permissionForm).forEach(key => {
    if (row[key] !== undefined) {
      permissionForm[key] = row[key];
    }
  });
  
  dialogVisible.value = true;
};

// 删除权限
const handleDelete = (row) => {
  if (hasChildren(row)) {
    ElMessage.warning('该权限包含子权限，无法删除');
    return;
  }
  
  ElMessageBox.confirm(
    `确定要删除权限 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const token = localStorage.getItem('token');
      await axios.delete(`/api/permissions/${row.id}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      // 从表格中移除
      removePermissionById(tableData.value, row.id);
      
      ElMessage.success('删除成功');
    } catch (error) {
      console.error('删除权限失败:', error);
      ElMessage.error('删除权限失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 重置权限表单
const resetPermissionForm = () => {
  permissionForm.id = null;
  permissionForm.name = '';
  permissionForm.code = '';
  permissionForm.type = 'menu';
  permissionForm.path = '';
  permissionForm.parentId = null;
  permissionForm.sort = 0;
  permissionForm.description = '';
  
  if (permissionFormRef.value) {
    permissionFormRef.value.resetFields();
  }
};

// 提交表单
const submitForm = async () => {
  if (!permissionFormRef.value) return;
  
  await permissionFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submitLoading.value = true;
    try {
      const token = localStorage.getItem('token');
      const headers = { Authorization: `Bearer ${token}` };
      
      if (dialogType.value === 'add') {
        // 创建权限
        const response = await axios.post('/api/permissions', permissionForm, { headers });
        const newPermission = response.data;
        
        if (permissionForm.parentId) {
          // 添加到父节点的children
          addChildPermission(tableData.value, permissionForm.parentId, newPermission);
        } else {
          // 添加为顶级节点
          tableData.value.push(newPermission);
        }
        
        ElMessage.success('权限创建成功');
      } else {
        // 更新权限
        const response = await axios.put(`/api/permissions/${permissionForm.id}`, permissionForm, { headers });
        
        // 更新表格中的权限
        updatePermissionById(tableData.value, permissionForm.id, response.data);
        
        ElMessage.success('权限更新成功');
      }
      
      dialogVisible.value = false;
    } catch (error) {
      console.error('保存权限失败:', error);
      ElMessage.error('保存权限失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    } finally {
      submitLoading.value = false;
    }
  });
};

// 检查是否有子权限
const hasChildren = (row) => {
  return row.children && row.children.length > 0;
};

// 从树形结构中移除指定ID的权限
const removePermissionById = (permissions, id) => {
  for (let i = 0; i < permissions.length; i++) {
    if (permissions[i].id === id) {
      permissions.splice(i, 1);
      return true;
    }
    
    if (permissions[i].children && permissions[i].children.length > 0) {
      if (removePermissionById(permissions[i].children, id)) {
        return true;
      }
    }
  }
  
  return false;
};

// 更新树形结构中指定ID的权限
const updatePermissionById = (permissions, id, newData) => {
  for (let i = 0; i < permissions.length; i++) {
    if (permissions[i].id === id) {
      // 保留children
      const children = permissions[i].children;
      permissions[i] = { ...newData };
      if (children) {
        permissions[i].children = children;
      }
      return true;
    }
    
    if (permissions[i].children && permissions[i].children.length > 0) {
      if (updatePermissionById(permissions[i].children, id, newData)) {
        return true;
      }
    }
  }
  
  return false;
};

// 添加子权限到指定父权限
const addChildPermission = (permissions, parentId, newPermission) => {
  for (let i = 0; i < permissions.length; i++) {
    if (permissions[i].id === parentId) {
      if (!permissions[i].children) {
        permissions[i].children = [];
      }
      permissions[i].children.push(newPermission);
      return true;
    }
    
    if (permissions[i].children && permissions[i].children.length > 0) {
      if (addChildPermission(permissions[i].children, parentId, newPermission)) {
        return true;
      }
    }
  }
  
  return false;
};

// 生成新的ID
const generateNewId = () => {
  // 简单实现，实际应该由后端生成
  const allIds = [];
  
  const collectIds = (permissions) => {
    if (!permissions) return;
    
    permissions.forEach(permission => {
      allIds.push(permission.id);
      if (permission.children) {
        collectIds(permission.children);
      }
    });
  };
  
  collectIds(tableData.value);
  
  return Math.max(...allIds) + 1;
};

// 计算权限总数（包括子权限）
const getPermissionCount = (permissions) => {
  let count = 0;
  const countRecursive = (items) => {
    if (!items) return;
    count += items.length;
    items.forEach(item => {
      if (item.children && item.children.length > 0) {
        countRecursive(item.children);
      }
    });
  };
  countRecursive(permissions);
  return count;
};
</script>

<style scoped>
.permission-list-container {
  padding: 10px;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title .el-icon {
  font-size: 22px;
  margin-right: 8px;
  color: #409EFF;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.header-operations :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 8px 16px;
}

.header-operations :deep(.el-icon) {
  font-size: 18px;
  margin-right: 5px;
}

/* 插图容器样式 */
.illustration-container {
  display: flex;
  align-items: center;
  background-color: #f0f9ff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.illustration-image {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.illustration-text h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #1f2f3d;
}

.illustration-text p {
  margin: 0;
  color: #5e6d82;
  font-size: 16px;
}

.table-card {
  margin-bottom: 20px;
}

/* 表格样式 */
.table-card :deep(.el-table) {
  font-size: 16px;
}

.table-card :deep(.el-table th) {
  font-size: 16px;
  padding: 12px 0;
}

.table-card :deep(.el-table td) {
  padding: 12px 0;
}

.cell-with-icon {
  display: flex;
  align-items: center;
}

.cell-with-icon .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
}

/* 对话框样式 */
:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  font-size: 16px;
}

:deep(.el-input__inner) {
  font-size: 16px;
}

:deep(.el-button) {
  font-size: 16px;
}

/* 响应式样式 */
@media screen and (max-width: 768px) {
  .illustration-container {
    flex-direction: column;
    text-align: center;
  }
  
  .illustration-image {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style> 